angular.module('directives.datepicker', [])
.directive('datePicker', function(){
    return {
        require: 'ngModel',
        link: function(scope, element, attributes, ngModelCtrl){


            if($.fn.datepicker === undefined){
                 throw new Error('jquery datepicker plugin is not loaded');
            }    

            //model changed    
            ngModelCtrl.$formatters.unshift(function(newValue){

                    if(angular.isDefined(newValue) && newValue !== null && !angular.isDate(newValue)){
                                    throw new Error('ng-model value must be a data object');
                    }


                    element.datepicker('setDate', newValue);	
                    return newValue;
                    });


            //input changed
            ngModelCtrl.$parsers.unshift(function(newValue){

                var dateFormat = element.datepicker( "option", "dateFormat" );

                try{
                    var parsed = $.datepicker.parseDate(dateFormat, newValue);
                }
                catch(err){
                    ngModelCtrl.$setValidity('date', false);
                    return;
                }

                ngModelCtrl.$setValidity('date', true);
                element.datepicker('setDate', parsed);  

                return newValue;
            });


            scope.$watch(attributes.datePicker, function(){
                    element.datepicker({
                            onSelect: function(value, picker){
                                            scope.$apply(function(){
                                                ngModelCtrl.$setViewValue(value);
                                            });

                                    }
                            });
                    });

        },
        scope: {
            model:'=ngModel'
        }
    };
});


